import 'dart:async';
import 'package:flutter/material.dart';
import '../models/asset_image.dart';
import '../../core/constants.dart';

/// 图片管理仓库
/// 
/// 开发思路分析：
/// 1. 仓库模式的核心 - 抽象数据来源，为业务层提供统一接口
/// 2. 职责单一原则 - 只负责图片数据的获取、管理、分类
/// 3. 可扩展设计 - 为V2.0的用户图片、网络图片预留接口
/// 4. 缓存策略 - 避免重复加载，提升性能
/// 
/// 这个类是数据访问层的核心，上层的ViewModel通过它获取图片数据
class ImageRepository {
  // 单例模式，确保全局只有一个实例
  static final ImageRepository _instance = ImageRepository._internal();
  factory ImageRepository() => _instance;
  ImageRepository._internal();
  
  // 内存缓存，避免重复创建图片模型对象
  final Map<String, AssetImageModel> _imageCache = {};
  final Map<ImageCategory, List<AssetImageModel>> _categoryCache = {};
  
  // 是否已初始化
  bool _isInitialized = false;
  
  /// 初始化图片仓库
  /// 
  /// 思路：项目启动时调用一次，预加载所有图片信息到内存
  Future<void> initialize() async {
    if (_isInitialized) return;
    
    debugPrint('🖼️ [ImageRepository] 开始初始化图片仓库...');
    
    try {
      // 创建内置图片模型
      await _loadBuiltInImages();
      
      // 按分类整理图片
      await _organizeCategorizedImages();
      
      _isInitialized = true;
      debugPrint('✅ [ImageRepository] 图片仓库初始化完成，共加载 ${_imageCache.length} 张图片');
    } catch (e) {
      debugPrint('❌ [ImageRepository] 初始化失败: $e');
      rethrow;
    }
  }
  
  /// 加载内置图片数据
  Future<void> _loadBuiltInImages() async {
    final builtInImages = [
      
      // 自然风光系列
      AssetImageModel.asset(
        id: 'nature_sunset',
        path: 'assets/images/nature/sunset.webp',
        name: '日落美景',
        category: '自然风光',
        description: '温暖的夕阳西下，橙红色的天空倒映在平静的湖面上',
        tags: const ['日落', '湖泊', '倒影', '温暖'],
        recommendedDifficulty: DifficultyLevel.easy,
      ),

      // AssetImageModel.asset(
      //   id: 'nature_ocean',
      //   path: 'assets/images/nature/ocean.jpg',
      //   name: '蔚蓝海洋',
      //   category: '自然风光',
      //   description: '碧蓝的海水拍打着白色的沙滩，海鸥在天空中飞翔',
      //   tags: const ['海洋', '沙滩', '海鸥', '蓝色'],
      //   recommendedDifficulty: DifficultyLevel.hard,
      // ),
      
      // 动物世界系列
      AssetImageModel.asset(
        id: 'animals_cat',
        path: 'assets/images/animals/cat.webp',
        name: '可爱猫咪',
        category: '动物世界',
        description: '毛茸茸的橘色小猫，正好奇地看着镜头',
        tags: const ['猫咪', '橘色', '可爱', '毛茸茸'],
        recommendedDifficulty: DifficultyLevel.easy,
      ),
      
      // AssetImageModel.asset(
      //   id: 'animals_dog',
      //   path: 'assets/images/animals/dog.jpg',
      //   name: '忠诚小狗',
      //   category: '动物世界',
      //   description: '金毛犬坐在草地上，舌头伸出来，表情很友善',
      //   tags: const ['狗狗', '金毛', '友善', '草地'],
      //   recommendedDifficulty: DifficultyLevel.medium,
      // ),
      
      // AssetImageModel.asset(
      //   id: 'animals_bird',
      //   path: 'assets/images/animals/bird.jpg',
      //   name: '美丽鸟类',
      //   category: '动物世界',
      //   description: '彩色的小鸟站在树枝上，羽毛色彩斑斓',
      //   tags: const ['鸟类', '彩色', '羽毛', '树枝'],
      //   recommendedDifficulty: DifficultyLevel.hard,
      // ),
      
      // // 建筑艺术系列
      // AssetImageModel.asset(
      //   id: 'architecture_castle',
      //   path: 'assets/images/architecture/castle.jpg',
      //   name: '古老城堡',
      //   category: '建筑艺术',
      //   description: '中世纪的石制城堡矗立在山顶，雄伟壮观',
      //   tags: const ['城堡', '中世纪', '石制', '雄伟'],
      //   recommendedDifficulty: DifficultyLevel.expert,
      // ),
      
      // AssetImageModel.asset(
      //   id: 'architecture_bridge',
      //   path: 'assets/images/architecture/bridge.jpg',
      //   name: '现代大桥',
      //   category: '建筑艺术',
      //   description: '跨越江河的现代化大桥，在夜晚灯火通明',
      //   tags: const ['大桥', '现代', '夜景', '灯光'],
      //   recommendedDifficulty: DifficultyLevel.hard,
      // ),
      
      // AssetImageModel.asset(
      //   id: 'architecture_temple',
      //   path: 'assets/images/architecture/temple.jpg',
      //   name: '传统建筑',
      //   category: '建筑艺术',
      //   description: '古典的东方建筑，红色的屋顶和金色的装饰',
      //   tags: const ['寺庙', '东方', '红色', '传统'],
      //   recommendedDifficulty: DifficultyLevel.medium,
      // ),
      AssetImageModel.asset(
  id: 'nature_mountain',
  path: 'assets/images/nature/mountain.jpg',  
  name: '山',
  category: '自然风光',
  description: '壮美的山',
  tags: const ['山', '风景', '自然'],
  recommendedDifficulty: DifficultyLevel.medium,
),

    ];

    
    
    // 缓存所有图片
    for (final image in builtInImages) {
      _imageCache[image.id] = image;
    }
  }
  
  /// 按分类整理图片
  Future<void> _organizeCategorizedImages() async {
    _categoryCache.clear();
    
    // 按分类分组
    final Map<String, List<AssetImageModel>> categoryGroups = {};
    for (final image in _imageCache.values) {
      categoryGroups.putIfAbsent(image.category, () => []).add(image);
    }
    
    // 转换为枚举分类
    for (final category in ImageCategory.values) {
      switch (category) {
        case ImageCategory.nature:
          _categoryCache[category] = categoryGroups['自然风光'] ?? [];
          break;
        case ImageCategory.animals:
          _categoryCache[category] = categoryGroups['动物世界'] ?? [];
          break;
        case ImageCategory.architecture:
          _categoryCache[category] = categoryGroups['建筑艺术'] ?? [];
          break;
        case ImageCategory.userImages:
          _categoryCache[category] = categoryGroups['用户图片'] ?? [];
          break;
        case ImageCategory.all:
          _categoryCache[category] = _imageCache.values.toList();
          break;
      }
    }
  }
  
  // =================== 公共API方法 ===================
  
  /// 获取所有图片
  List<AssetImageModel> getAllImages() {
    _ensureInitialized();
    return _imageCache.values.toList();
  }
  
  /// 根据分类获取图片
  List<AssetImageModel> getImagesByCategory(ImageCategory category) {
    _ensureInitialized();
    return List.from(_categoryCache[category] ?? []);
  }
  
  /// 根据ID获取图片
  AssetImageModel? getImageById(String id) {
    _ensureInitialized();
    return _imageCache[id];
  }
  
  /// 根据路径获取图片
  AssetImageModel? getImageByPath(String path) {
    _ensureInitialized();
    return _imageCache.values.where((img) => img.path == path).firstOrNull;
  }
  
  /// 搜索图片
  List<AssetImageModel> searchImages(String keyword) {
    _ensureInitialized();
    if (keyword.isEmpty) return getAllImages();
    
    return _imageCache.values
        .where((image) => image.matchesKeyword(keyword))
        .toList();
  }
  
  /// 根据难度筛选图片
  List<AssetImageModel> getImagesByDifficulty(DifficultyLevel difficulty) {
    _ensureInitialized();
    return _imageCache.values
        .where((image) => image.recommendedDifficulty == difficulty)
        .toList();
  }
  
  /// 获取随机图片
  AssetImageModel? getRandomImage([ImageCategory? category]) {
    _ensureInitialized();
    final images = category == null 
        ? getAllImages() 
        : getImagesByCategory(category);
    
    if (images.isEmpty) return null;
    
    final randomIndex = DateTime.now().millisecondsSinceEpoch % images.length;
    return images[randomIndex];
  }
  
  /// 获取推荐图片（基于难度和分类）
  List<AssetImageModel> getRecommendedImages({
    DifficultyLevel? difficulty,
    ImageCategory? category,
    int limit = 6,
  }) {
    _ensureInitialized();
    
    var images = getAllImages();
    
    // 按分类筛选
    if (category != null && category != ImageCategory.all) {
      images = getImagesByCategory(category);
    }
    
    // 按难度筛选
    if (difficulty != null) {
      images = images
          .where((img) => img.recommendedDifficulty == difficulty)
          .toList();
    }
    
    // 限制数量
    if (images.length > limit) {
      images = images.take(limit).toList();
    }
    
    return images;
  }
  
  /// 获取图片分类统计
  Map<ImageCategory, int> getCategoryStats() {
    _ensureInitialized();
    return _categoryCache.map((category, images) => 
        MapEntry(category, images.length));
  }
  
  /// 获取所有可用的图片路径（与AppConstants兼容）
  List<String> getAvailableImagePaths() {
    _ensureInitialized();
    return _imageCache.values.map((img) => img.path).toList();
  }
  
  // =================== V2.0功能预留 ===================
  
  /// 添加用户图片（V2.0功能预留）
  Future<bool> addUserImage(AssetImageModel userImage) async {
    try {
      _imageCache[userImage.id] = userImage;
      await _organizeCategorizedImages(); // 重新整理分类
      
      debugPrint('✅ [ImageRepository] 添加用户图片成功: ${userImage.name}');
      return true;
    } catch (e) {
      debugPrint('❌ [ImageRepository] 添加用户图片失败: $e');
      return false;
    }
  }
  
  /// 删除用户图片（V2.0功能预留）
  Future<bool> removeUserImage(String imageId) async {
    try {
      final image = _imageCache[imageId];
      if (image == null || !image.isUserGenerated) {
        return false; // 不能删除内置图片
      }
      
      _imageCache.remove(imageId);
      await _organizeCategorizedImages();
      
      debugPrint('✅ [ImageRepository] 删除用户图片成功: $imageId');
      return true;
    } catch (e) {
      debugPrint('❌ [ImageRepository] 删除用户图片失败: $e');
      return false;
    }
  }
  
  /// 清除缓存
  void clearCache() {
    _imageCache.clear();
    _categoryCache.clear();
    _isInitialized = false;
    debugPrint('🧹 [ImageRepository] 缓存已清除');
  }
  
  /// 刷新仓库数据
  Future<void> refresh() async {
    clearCache();
    await initialize();
  }
  
  // =================== 私有辅助方法 ===================
  
  /// 确保仓库已初始化
  void _ensureInitialized() {
    if (!_isInitialized) {
      throw StateError('ImageRepository 未初始化，请先调用 initialize() 方法');
    }
  }
  
  // /// 验证图片路径是否存在（开发时用于调试）
  // Future<bool> _validateImagePath(String path) async {
  //   try {
  //     // 简单验证，实际项目中可以更详细
  //     return path.isNotEmpty && path.startsWith('assets/');
  //   } catch (e) {
  //     return false;
  //   }
  // }
  
  /// 获取调试信息
  Map<String, dynamic> getDebugInfo() {
    return {
      'initialized': _isInitialized,
      'totalImages': _imageCache.length,
      'categories': _categoryCache.keys.map((c) => c.displayName).toList(),
      'cacheSize': _imageCache.length,
    };
  }
}

/// 图片仓库工厂类
/// 
/// 设计思路：提供便捷的创建方法，支持不同的初始化策略
class ImageRepositoryFactory {
  /// 创建并初始化图片仓库
  static Future<ImageRepository> create() async {
    final repository = ImageRepository();
    await repository.initialize();
    return repository;
  }
  
  /// 创建测试用的图片仓库（预留）
  static ImageRepository createForTesting() {
    final repository = ImageRepository();
    // 可以在这里添加测试用的图片数据
    return repository;
  }
}

/// 图片仓库扩展方法
extension ImageRepositoryExtensions on ImageRepository {
  /// 检查是否有足够的图片用于指定难度
  bool hasEnoughImagesForDifficulty(DifficultyLevel difficulty, int minCount) {
    final images = getImagesByDifficulty(difficulty);
    return images.length >= minCount;
  }
  
  /// 获取最受欢迎的分类（图片数量最多）
  ImageCategory? getMostPopularCategory() {
    final stats = getCategoryStats();
    if (stats.isEmpty) return null;
    
    ImageCategory? mostPopular;
    int maxCount = 0;
    
    for (final entry in stats.entries) {
      if (entry.key != ImageCategory.all && entry.value > maxCount) {
        maxCount = entry.value;
        mostPopular = entry.key;
      }
    }
    
    return mostPopular;
  }
  
  /// 按标签获取图片
  List<AssetImageModel> getImagesByTag(String tag) {
    return getAllImages()
        .where((image) => image.tags.contains(tag))
        .toList();
  }
}
